<template>
  <div class="app-container">
    <!-- 修改站点选择 -->
    <el-form :inline="true">
      <el-form-item label="选择站点">
        <el-select
          v-model="selectedStation"
          placeholder="请选择站点"
          @change="handleStationChange"
          clearable
        >
          <el-option
            v-for="item in stationOptions"
            :key="item.id"
            :label="item.stationName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 顶部卡片统计 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :span="4">
        <div class="card total-stations">
          <div class="card-body">
            <div class="card-title">站点总数</div>
            <div class="card-value">{{ statistics.totalStations || 0 }}</div>
          </div>
          <div class="card-icon">
            <el-icon><Location /></el-icon>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="card total-records">
          <div class="card-body">
            <div class="card-title">总刷卡次数</div>
            <div class="card-value">{{ statistics.totalRecords }}</div>
          </div>
          <div class="card-icon">
            <el-icon><DataLine /></el-icon>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="card elderly-total">
          <div class="card-body">
            <div class="card-title">老年人刷卡数</div>
            <div class="card-value">{{ statistics.totalElderlyRecords || 0 }}</div>
          </div>
          <div class="card-icon">
            <el-icon><User /></el-icon>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="card today-records">
          <div class="card-body">
            <div class="card-title">今日刷卡</div>
            <div class="card-value">{{ statistics.todayRecords }}</div>
          </div>
          <div class="card-icon">
            <el-icon><Timer /></el-icon>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="card elderly-today">
          <div class="card-body">
            <div class="card-title">今日老年人刷卡</div>
            <div class="card-value">{{ statistics.todayElderlyRecords || 0 }}</div>
          </div>
          <div class="card-icon">
            <el-icon><PieChart /></el-icon>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="mt20">
      <!-- 左侧图表 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>刷卡趋势</span>
              <el-radio-group v-model="trendTimeRange" size="small">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
                <el-radio-button label="quarter">本季度</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-wrapper">
            <div ref="trendChartRef" style="height: 350px"></div>
          </div>
        </el-card>

        <el-card class="mt20">
          <template #header>
            <div class="card-header">
              <span>站点刷卡排行</span>
              <el-select v-model="rankTimeRange" size="small">
                <el-option label="今日" value="today" />
                <el-option label="本周" value="week" />
                <el-option label="本月" value="month" />
                <el-option label="本季度" value="quarter" />
                <el-option label="本年" value="year" />
              </el-select>
            </div>
          </template>
          <div class="chart-wrapper">
            <div ref="rankChartRef" style="height: 350px"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧图表 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>年龄分布</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <div ref="ageChartRef" style="height: 300px"></div>
          </div>
        </el-card>

        <el-card class="mt20">
          <template #header>
            <div class="card-header">
              <span>性别比例</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <div ref="genderChartRef" style="height: 300px"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getStatistics, getTrendData, getRankData } from '@/api/jzzgl/statistics'
import { listStation } from "@/api/jzzgl/station"
import { Location, DataLine, Timer, PieChart, User } from '@element-plus/icons-vue'

// 统计数据
const statistics = ref({
  totalStations: 0,
  totalRecords: 0,
  totalElderlyRecords: 0,
  todayRecords: 0,
  todayElderlyRecords: 0
})

// 图表引用
const trendChartRef = ref(null)
const rankChartRef = ref(null)
const ageChartRef = ref(null)
const genderChartRef = ref(null)

// 图表实例
let trendChart = null
let rankChart = null
let ageChart = null
let genderChart = null

// 时间范围选择
const trendTimeRange = ref('week')
const rankTimeRange = ref('today')

// 站点选择相关
const selectedStation = ref(null)
const stationOptions = ref([])

// 获取站点列表
const getStationOptions = async () => {
  try {
    const res = await listStation({ pageSize: 100 }) // 获取足够多的站点
    stationOptions.value = res.rows
  } catch (error) {
    console.error('获取站点列表失败:', error)
  }
}

// 处理站点选择变化
const handleStationChange = () => {
  getStatisticsData()
}

// 初始化图表基本配置
const initCharts = () => {
  // 刷卡趋势图基本配置
  trendChart = echarts.init(trendChartRef.value)
  trendChart.setOption({
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['刷卡人次', '老年人次']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '刷卡人次',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '老年人次',
        type: 'line',
        smooth: true,
        data: []
      }
    ]
  })

  // 站点排行图基本配置
  rankChart = echarts.init(rankChartRef.value)
  rankChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: []
    },
    series: [
      {
        type: 'bar',
        data: []
      }
    ]
  })

  // 年龄分布图基本配置
  ageChart = echarts.init(ageChartRef.value)
  ageChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      left: 'center'
    },
    series: [
      {
        name: '年龄分布',
        type: 'pie',
        radius: ['30%', '60%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{c}人 ({d}%)'
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10
        },
        data: []
      }
    ]
  })

  // 性别比例图基本配置
  genderChart = echarts.init(genderChartRef.value)
  genderChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      left: 'center'
    },
    series: [
      {
        name: '性别比例',
        type: 'pie',
        radius: '55%',
        center: ['50%', '45%'],
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{c}人 ({d}%)'
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10
        },
        data: []
      }
    ]
  })
}

// 获取统计数据并更新所有图表
const getStatisticsData = async () => {
  try {
    // 只传递 stationId
    const params = selectedStation.value ? { stationId: selectedStation.value } : {}

    console.log('发送的统计请求参数:', params)

    // 获取基础统计数据
    const res = await getStatistics(params)
    console.log('获取到的统计数据:', res.data)
    statistics.value = res.data

    // 更新年龄分布和性别比例图
    updateAgeAndGenderCharts(res.data)

    // 获取并更新趋势图数据
    await getTrendChartData()

    // 获取并更新排行图数据
    await getRankChartData()
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取趋势数据
const getTrendChartData = async () => {
  try {
    const params = {
      timeRange: trendTimeRange.value
    }
    // 只在有选择站点时添加 stationId
    if (selectedStation.value) {
      params.stationId = selectedStation.value
    }

    console.log('发送的趋势请求参数:', params)
    const res = await getTrendData(params)

    trendChart.setOption({
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          let result = params[0].axisValue + '<br/>'
          params.forEach(item => {
            result += `${item.seriesName}：${item.value}<br/>`
          })
          return result
        }
      },
      legend: {
        data: ['刷卡人次', '老年人次']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: res.data.dates,
        axisLabel: {
          rotate: trendTimeRange.value === 'year' ? 45 : 0  // 年度数据时旋转标签
        }
      },
      yAxis: {
        type: 'value',
        name: '刷卡次数'
      },
      series: [
        {
          name: '刷卡人次',
          type: 'line',
          smooth: true,
          data: res.data.series.total,
          itemStyle: {
            color: '#36a3f7'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(54,163,247,0.3)'
              }, {
                offset: 1,
                color: 'rgba(54,163,247,0)'
              }]
            }
          }
        },
        {
          name: '老年人次',
          type: 'line',
          smooth: true,
          data: res.data.series.elderly,
          itemStyle: {
            color: '#34bfa3'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(52,191,163,0.3)'
              }, {
                offset: 1,
                color: 'rgba(52,191,163,0)'
              }]
            }
          }
        }
      ]
    })
  } catch (error) {
    console.error('获取趋势数据失败:', error)
  }
}

// 获取排行数据
const getRankChartData = async () => {
  try {
    const params = {
      timeRange: rankTimeRange.value
    }
    // 只在有选择站点时添加 stationId
    if (selectedStation.value) {
      params.stationId = selectedStation.value
    }

    console.log('发送的排行请求参数:', params)
    const res = await getRankData(params)

    const stations = res.data.stations
    // 对数据进行排序，确保按刷卡次数降序排列
    stations.sort((a, b) => b.count - a.count)

    rankChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params) {
          const data = params[0]
          return `${data.name}<br/>刷卡次数：${data.value}`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        name: '刷卡次数'
      },
      yAxis: {
        type: 'category',
        data: stations.map(item => item.stationName),
        axisLabel: {
          formatter: function(value) {
            if (value.length > 8) {
              return value.substring(0, 8) + '...'
            }
            return value
          }
        }
      },
      series: [
        {
          name: '刷卡次数',
          type: 'bar',
          data: stations.map(item => item.count),
          itemStyle: {
            color: function(params) {
              // 为不同排名设置不同颜色
              const colors = ['#ff4949', '#ffa74d', '#4fc08d', '#36a3f7', '#34bfa3']
              return colors[params.dataIndex] || '#909399'
            }
          },
          label: {
            show: true,
            position: 'right',
            formatter: '{c}'
          }
        }
      ]
    })
  } catch (error) {
    console.error('获取排行数据失败:', error)
  }
}

// 更新年龄分布和性别比例图
const updateAgeAndGenderCharts = (data) => {
  console.log('更新图表的数据:', data)

  // 更新年龄分布图
  if (ageChart) {
    // 直接使用后端返回的数组数据
    const ageData = data.ageDistribution || []
    console.log('年龄分布数据:', ageData)

    // 清除现有数据
    ageChart.clear()

    // 重新设置完整的配置
    ageChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'horizontal',
        bottom: 0,
        left: 'center'
      },
      series: [
        {
          name: '年龄分布',
          type: 'pie',
          radius: ['30%', '60%'],
          center: ['50%', '45%'],
          avoidLabelOverlap: true,
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}\n{c}人 ({d}%)'
          },
          labelLine: {
            show: true,
            length: 15,
            length2: 10
          },
          // 直接使用后端返回的数组数据
          data: ageData
        }
      ]
    }, true)
  }

  // 更新性别比例图
  if (genderChart) {
    // 直接使用后端返回的数组数据
    const genderData = data.genderRatio || []
    console.log('性别比例数据:', genderData)

    // 清除现有数据
    genderChart.clear()

    // 重新设置完整的配置
    genderChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'horizontal',
        bottom: 0,
        left: 'center'
      },
      series: [
        {
          name: '性别比例',
          type: 'pie',
          radius: '55%',
          center: ['50%', '45%'],
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}\n{c}人 ({d}%)'
          },
          labelLine: {
            show: true,
            length: 15,
            length2: 10
          },
          // 直接使用后端返回的数组数据
          data: genderData
        }
      ]
    }, true)
  }
}

// 监听时间范围变化
watch(trendTimeRange, () => {
  getTrendChartData()
})

watch(rankTimeRange, () => {
  getRankChartData()
})

// 监听窗口大小变化
const handleResize = () => {
  trendChart?.resize()
  rankChart?.resize()
  ageChart?.resize()
  genderChart?.resize()
}

onMounted(() => {
  getStationOptions()
  initCharts()
  getStatisticsData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  rankChart?.dispose()
  ageChart?.dispose()
  genderChart?.dispose()
})

// 修改导出按钮操作
const handleExport = async () => {
  try {
    loading.value = true;
    const params = {
      ...queryParams.value,
      stationId: queryParams.value.id,
      pageNum: 1,
      pageSize: 10000,
      orderByColumn: 'createTime',
      isAsc: 'desc'
    };
    if (dateRange.value && dateRange.value.length === 2) {
      params.beginTime = dateRange.value[0];
      params.endTime = dateRange.value[1];
    }

    console.log('导出参数:', params);
    const res = await listRecord(params);

    // 在前端处理65岁及以上的过滤
    let exportData = res.rows;
    if (params.ageFilter === '65+') {
      exportData = res.rows.filter(item => calculateAge(item.birthday) >= 65);
    }

    if (!exportData || exportData.length === 0) {
      ElMessage.warning("没有数据可导出");
      return;
    }

    // 修改动态导入的写法
    const Excel = await import('@/vendor/Export2Excel')

    const tHeader = ['站点名称', '姓名', '身份证号', '性别', '民族', '年龄', '住址', '刷卡时间']
    const filterVal = ['stationName', 'name', 'idNumber', 'gender', 'nation', 'birthday', 'address', 'createTime']
    const data = formatJson(filterVal, exportData)

    Excel.export_json_to_excel({
      header: tHeader,
      data,
      filename: '刷卡记录',
      autoWidth: true,
      bookType: 'xlsx'
    })

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败：" + error.message);
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.panel-group {
  margin-top: 18px;
}

.card {
  height: 108px;
  position: relative;
  overflow: hidden;
  color: #fff;
  border-radius: 4px;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 5px;
}

.total-stations {
  background: #40c9c6;
}

.total-records {
  background: #36a3f7;
}

.elderly-total {
  background: #ffa74d;
}

.today-records {
  background: #f4516c;
}

.elderly-today {
  background: #34bfa3;
}

.card-body {
  flex: 1;
}

.card-title {
  font-size: 16px;
  margin-bottom: 10px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
}

.card-icon {
  font-size: 42px;
  opacity: 0.8;
  margin-left: 10px;
}

.mt20 {
  margin-top: 20px;
}

.chart-wrapper {
  background: #fff;
  padding: 16px;
  min-height: 300px;
  position: relative;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-card {
  margin-bottom: 20px;
}

.el-card:last-child {
  margin-bottom: 0;
}

/* 添加站点选择的样式 */
.el-form {
  margin-bottom: 20px;
}
</style>
